﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LCA.Utils;
using System.Web.Script.Serialization;
using Composite.Data;
using LCA.Data;
using LCA.Common.Extensions;

public partial class Admin_LCAFlow_CreateMultipleFlows : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            RefreshComponents();
        }

    }

    protected void lnkRefresh_Click(object sender, EventArgs e)
    {
        PageHelper.AdminPageRedirect(Page, "CreateMultipleFlows.aspx");
    }

    protected void lnkAddMore_Click(object sender, EventArgs e)
    {
        PageHelper.AdminPageRedirect(Page, "CreateMultipleFlows.aspx");
    }

    protected void lnkEdit_Click(object sender, EventArgs e)
    {
        PageHelper.AdminPageRedirect(Page, "ManageFlows.aspx");
    }

    public void RefreshComponents()
    {
        plhInit.Visible = true;
        ctlFlowRow.RefreshComponents();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        // Parse JSON string from textbox: txtFlowsRaw.Text
        int count = 0;
        try
        {
            var table = new JavaScriptSerializer().Deserialize<dynamic>(txtFlowsRaw.Text);
            // int.Parse("xxx");
            using (DataConnection connection = new DataConnection())
            {
                LCA.Data.Flow flow = null;
                foreach (var row in table)
                {
                    string name = row["Name"].ToString();
                    string unit_id = row["Unit"];

                    flow = connection.CreateNew<LCA.Data.Flow>();
                    flow.FlowId = Sequences.FlowId.NextVal.Value;
                    flow.CreatedDate = DateTime.Now;

                    flow.Name = name;
                    flow.Unit = unit_id.ToGuid().Value;
                    flow.TechnoSphere = true;

                    connection.Add(flow);
                    count++;
                }
            }

        }
        catch (Exception ex)
        {
            plhInit.Visible = false;
            plhResult.Visible = false;
            plhError.Visible = false;

            plhError.Visible = true;
            litError.Text = "<strong>Warning</strong>: Error has been occurred. Please try again."; 
            return;
        }

        // Notify user that flows have been created.
        plhInit.Visible = false;
        plhResult.Visible = false;
        plhError.Visible = false;

        plhResult.Visible = true;
        litResult.Text = string.Format("<strong>Success</strong>: You have added '{0}' flows", count);
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        PageHelper.AdminPageRedirect(Page, "ManageFlows.aspx");
    }

}